package com.xiangxiangjd.kj.papersstar.controller.api;

import com.google.common.collect.Lists;
import com.xiangxiangjd.kj.papersstar.bean.Answer;
import com.xiangxiangjd.kj.papersstar.bean.Topic;
import com.xiangxiangjd.kj.papersstar.controller.BaseController;
import com.xiangxiangjd.kj.papersstar.controller.export.TopicExprot;
import com.xiangxiangjd.kj.papersstar.controller.helper.$;
import com.xiangxiangjd.kj.papersstar.controller.model.ApiResultModel;
import com.xiangxiangjd.kj.papersstar.utils.StringUtils;
import com.xiangxiangjd.kj.papersstar.utils.excel.ExportExcel;
import com.xiangxiangjd.kj.papersstar.utils.excel.ImportExcel;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 肖守凯
 * @since 2021-01-21
 */
@RestController
@RequestMapping("/api/topic")
@Slf4j
public class TopicApi extends BaseController {

    /**
     * 插入试题
     *
     * @param topic
     * @return
     */

    @PutMapping("putTopic")
    public ApiResultModel putTopic(@RequestBody Topic topic) {
        return topicService.addTopicAnswer(topic);
    }

    /**
     * 下载导入的ex 的表格
     */
    @RequestMapping(value = "/improTopic/template")
    public void importFileTemplate(HttpServletResponse response) {
        try {
            String fileName = "导入问题.xlsx";
            List<TopicExprot> list = Lists.newArrayList();
            new ExportExcel("导入问题", TopicExprot.class, 1).setDataList(list).write(response, fileName).dispose();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("导入模板下载失败！失败信息：" + e.getMessage());
        }
    }

    /**
     * 导入Excel
     *
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "import/{QuestionnaireId}")
    public ApiResultModel importFile(@RequestParam("file") MultipartFile file, @PathVariable("QuestionnaireId") String questionnaireId) {
        try {
            //第2行开始 获取数组
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<TopicExprot> list = ei.getDataList(TopicExprot.class);
            //根据题目对应答案
            Map<Integer, Topic> anMap = new LinkedHashMap<>(16);
            int count = 3;
            for (TopicExprot topicExprot : list) {
                if (StringUtils.isBlank(topicExprot.getNo())) return $.error("第" + count + "行 ,请填写 问题序号!");
                Integer key;
                //序号
                try {
                    key = Integer.parseInt(topicExprot.getNo());
                } catch (Exception e) {
                    return $.error("第" + count + "行 , 问题序号 必须为数字!");
                }
                //如果包含
                if (anMap.containsKey(key)) {

                    Topic topic = anMap.get(key);

                    if (StringUtils.isBlank(topicExprot.getKey())) return $.error("第" + count + "行 , 答案选项不为 空!");
                    if (StringUtils.isBlank(topicExprot.getValue())) return $.error("第" + count + "行 , 答案值不为 空!");
                    if (StringUtils.isBlank(topicExprot.getAnswerOrder()))
                        return $.error("第" + count + "行 , 答案序号不可为 空!");
                    //给答案赋值
                    Answer answer = new Answer();
                    answer.setAnswerKey(topicExprot.getKey());
                    answer.setAnswerValue(topicExprot.getValue());
                    answer.setAnswerOrder(topicExprot.getAnswerOrder());
                    topic.addAnswers(answer);
                    log.info("添加答案成:" + topic.toString());

                } else {
                    if (topicExprot.getTopicType().equals("1") && StringUtils.isBlank(topicExprot.getAnswerId()))
                        return $.error("第" + count + "行 , 请填写问题的正确答案!");
                    //当不包含的时候
                    Topic topic = new Topic();
                    topic.setQuestionnaireId(questionnaireId);
                    topic.setAnswerId(topicExprot.getAnswerId());
                    topic.setTopicType(topicExprot.getTopicType());
                    topic.setTopicTitle(topicExprot.getTopicTitle());
                    //初始化 对象
                    topic.setAnswers(new ArrayList<Answer>());
                    //保存 试题
                    anMap.put(key, topic);
                }
                count++;
            }

            // 导入数据条数
            anMap.forEach((k, v) -> {
                System.out.println("开始导入数据");
                ApiResultModel apiResultModel =topicService.addTopicAnswer(v);
            });
            // 导入成功
            return $.success();
        } catch (IOException e) {

        } catch (InvalidFormatException e) {

        } catch (IllegalAccessException e) {

        } catch (InstantiationException e) {

        }
        return $.error("受到一股神秘的力量 发生了错误!");
    }



}
